from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from tools.myLogger import logger
import traceback

class BasePage():
    """
    基础页面操作封装
    """
    def __init__(self, driver):
        """
        初始化方法
        """
        # self.driver = webdriver.Chrome()
        self.driver = driver
        # self.driver.maximize_window()
        logger.info("设置隐式等待时长为10s")
        self.driver.implicitly_wait(20)

    def my_get_text(self, ele):
        logger.info(f"获取元素的文本信息，元素为{ele}")
        try:
            self.my_find_ele(ele)
            return self.ele.text
        except:
            error = traceback.format_exc()
            logger.error("元素定位失败，元素值{}，报错信息{}".format(ele, error))
            # raise


    def my_add_cookie(self, cookie):
        self.driver.add_cookie(cookie)

    def my_find_ele(self, ele):
        """
        查找元素
        :param ele:
        :return:
        """
        logger.info(f"查找元素，元素为{ele}")
        try:
            self.ele = WebDriverWait(self.driver, 20, 0.5).until(EC.presence_of_element_located(ele))
        except Exception as e:
            logger.warning(e)
            raise

    def my_click(self, ele):
        """
        点击元素
        :param ele:
        :return:
        """
        self.my_find_ele(ele)
        self.ele.click()

    def my_send_keys(self, ele, value):
        """
        元素内输入数据
        :param ele:
        :param value:
        :return:
        """
        self.my_find_ele(ele)
        self.ele.send_keys(value)

    def my_get_url(self, url):
        self.driver.get(url)

    def my_quit(self):
        self.driver.quit()
